package com.mu.service.impl;

import com.alibaba.fastjson.JSON;
import com.mu.common.MsgType;
import com.mu.domain.InputMessage;
import com.mu.domain.MessageEntity;
import com.mu.domain.UserMessage;
import com.mu.manger.MessageCallBack;
import com.mu.manger.MessageThread;
import com.mu.service.MessageService;
import com.mu.websocket.XunListener;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author shang
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Value("${xun.hosturl}")
    public String hosturl;
    @Value("${xun.apisecret}")
    public String apisecret;
    @Value("${xun.apikey}")
    public String apikey;
    @Value("${xun.appid}")
    public String appid;

    @Override
    public void sendMessage(InputMessage request, HttpServletResponse response) {
        MessageCallBack messageBack = MessageCallBack.getSingleton();
        String userId = request.getFromUserName();
        String question = request.getContent();
        //不在处理过程中的话，再发送消息
        if (!messageBack.isRepeatQuestion(userId, question)) {
            //发送消息
            messageBack.setQuestion(userId, question);
            sendMessage(userId, question);
        }
        messageBack.userQuestionNumberAdd(userId, question);
        //接收消息并回复
        getBackMessage(messageBack, response, request);

    }

    private void getBackMessage(MessageCallBack messageBack, HttpServletResponse response, InputMessage request){
        //获取回答
        long outTime = 0L;
        String userId = request.getFromUserName();
        String question = request.getContent();
        try {
            while (true) {
                UserMessage userMessage = messageBack.getBackUserMessage(userId, question);
                if (userMessage != null && !StringUtils.isEmpty(userMessage.getAnswer())) {
                    String answer = userMessage.getAnswer();
                    log.info("获取回答，删除记录 answer：{}", answer);
                    messageBack.remove(userId, question);
                    response(request, response, answer);
                    return;
                }
                if (outTime > 1000 * 4) {
                    if (userMessage == null || userMessage.getNumber() == 3) {
                        log.info("获取回答失败，删除记录");
                        messageBack.remove(userId, question);
                        response(request, response, "我要思考一下，你再重新问一次吧");
                        return;
                    }
                    return;
                }
                Thread.sleep(500);
                outTime = outTime + 500;
            }
        }catch (Exception e){
            log.error("接收AI消息失败", e);
        }
    }

    void response(InputMessage request, HttpServletResponse response, String backMessage){
        String result = "返回失败，请重试";
        // 返回时间
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;
        try {
            result = "<xml>" +
                    "<ToUserName><![CDATA[" + request.getFromUserName() + "]]></ToUserName>" +
                    "<FromUserName><![CDATA[" + request.getToUserName() + "]]></FromUserName>" +
                    "<CreateTime>" + returnTime + "</CreateTime>" +
                    "<MsgType><![CDATA[" + MsgType.Text + "]]></MsgType>" +
                    "<Content><![CDATA[" + backMessage + "]]></Content>" +
                    "</xml>";
            String respMessage = new String(result.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            log.info("result:{}", result);
            response.getWriter().write(respMessage);
        }catch (Exception e){
            log.error("返回结果失败", e);
            try {
                response.getWriter().write(result);
            }catch (Exception ex){
                log.error("返回结果再次失败", e);
            }
        }

    }

    @Override
    public void sendMessage(String userId, String msg) {

        try{
            // 构建鉴权url
            String authUrl = getAuthUrl(hosturl, apikey, apisecret);
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            for (int i = 0; i < 1; i++) {
                WebSocket webSocket = client.newWebSocket(request, new XunListener());
                MessageThread messageThread = new MessageThread(webSocket, userId, msg, appid);
                messageThread.start();
            }
        }catch (Exception e){
            System.out.println("e = " + e.getMessage());
        }

    }

    /**
     * 鉴权方法
     * @param hostUrl 地址
     * @param apiKey apikey
     * @param apiSecret api
     * @return 结果
     * @throws Exception 异常
     */
    private static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        //Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        //拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).
                addQueryParameter("date", date).
                addQueryParameter("host", url.getHost()).
                build();
        return httpUrl.toString();
    }

}
